package com.learn.handler;

import com.learn.pojo.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @program: rmi
 * @description
 * @author: luffy
 * @create: 2020-08-17 14:21
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    //1.定义成员变量
    private ChannelHandlerContext context;//事件
    private String result;
    private RpcRequest request;
    //2.实现channelActive 客户端和服务器连接，该方法自动执行

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //初始化context
        this.context = ctx;
    }


    //3.实现channelRead 当我们读取到服务器数据，该方法自动执行

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        notify();
    }


    //4.将客户端的数据写到服务器

    public synchronized Object call() throws Exception {
        //context给服务器写数据
        context.writeAndFlush(request);
        wait();
        return result;
    }

    //5.设置参数的方法
    public void setParam(RpcRequest request) {
        this.request = request;

    }
}
